package com.clw.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.clw.template.entity.SysAdmin;
import com.clw.template.entity.SysRole;
import com.clw.template.entity.SysRolePermissionRelation;
import com.clw.template.mapper.SysRoleMapper;
import com.clw.template.service.ISysRolePermissionRelationService;
import com.clw.template.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clw.template.service.ISysAdminService;
import com.clw.template.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 后台用户角色表 服务实现类
 * </p>
 *
 * @author clw
 * @since 2019-11-02
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysAdminService sysUserService;
    @Autowired
    private ISysRolePermissionRelationService sysRolePermissionRelationService;

    @Override
    @Transactional
    public CommonResult<SysRole> deleted(Long id) {
        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().apply("FIND_IN_SET("+id+",roles)");
        Integer integer = sysUserService.count(queryWrapper);
        if (integer > 0){
            return CommonResult.failed("角色有用户在用，不能删除");
        }
        //删除角色与权限的关联表
        QueryWrapper<SysRolePermissionRelation> qw2 = new QueryWrapper<>();
        qw2.lambda().eq(SysRolePermissionRelation::getRoleId,id);
        sysRolePermissionRelationService.remove(qw2);
        //删除角色
        removeById(id);
        return CommonResult.success();
    }
}
